<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XHR Level2</title>
    <link rel="stylesheet" href="./bootstrap.css">
    <script src="./jQuery.js"></script>
</head>
<body>
    <form action="" id="form">
                                        <!-- 关闭自动填充选项 -->
        <input type="text" name="uname" autocomplete="off"> <br>
        <input type="password" name="pwd">
        <button type="submit">提交</button>
    </form>

    <br><br><br>

    <input type="file" id="file">
    <button id="btn">上传文件</button>

    <!-- bootstrap进度条 -->
    <div class="progress" style="width: 400px;margin: 15px;">
        <div class="progress-bar progress-bar-striped active" style="width: 0%;" id="percent"> 
            0%
        </div>
    </div>
    
    <br>
    <img src="" alt="" id="img" width="800">



<script>
    // Ajax操作很耗时 ，且无法预知时间 ，新版XHR对象增加了timeout属性 ，可设置请求时限
    var xhr = new XMLHttpRequest();

    xhr.timeout = 30;
    // 超时后停止请求 ，并执行回调函数
    xhr.ontimeout = function(){
        console.log('请求超时！');
    }

    xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks');
    xhr.send();

    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            console.log(xhr.responseText);
        }
    }


    // formData对象
    var fd = new FormData();
    fd.append('username', '张三');
    fd.append('password', '123456');

    var xhr2 = new XMLHttpRequest();
    xhr2.open('POST', 'http://www.liulongbin.top:3006/api/formdata');
    xhr2.send(fd);

    xhr2.onreadystatechange = function(){
        if(xhr2.readyState == 4 && xhr2.status == 200){
            console.log(JSON.parse(xhr2.responseText));
        }
    }


    // 通过formData提交表单
    var form = document.querySelector('#form');
    form.addEventListener('submit', function(e){
        e.preventDefault();

        var fd = new FormData(form);

        var xhr3 = new XMLHttpRequest();
        xhr3.open('POST', 'http://www.liulongbin.top:3006/api/formdata');
        xhr3.send(fd);

        xhr3.addEventListener('readystatechange', function(){
            if(xhr3.readyState == 4 && xhr3.status == 200){
                console.log(JSON.parse(xhr3.responseText));
            }
        })
    })


    // 文件上传
    var btn = document.querySelector('#btn');
    btn.addEventListener('click', function(){
                                                // 获取用户选择的文件列表
        var files = document.querySelector('#file').files;
        if(files.length <= 0){
            return alert('请选择要上传的文件');
        }
        
        var fd = new FormData();
        fd.append('touxiang', files[0]);

        var xhr4 = new XMLHttpRequest();

        // 监听文件上传进度
        xhr4.upload.onprogress = function(e){
            if(e.lengthComputable){   // 值为true表示可计算出上传进度
            // 已上传的大小/文件的大小
                var percentComplete = Math.ceil((e.loaded / e.total)*100)
                // console.log(procentComplete);
                $('#percent').attr('style', `width: ${percentComplete}%;`).html(`${percentComplete}%`);
            }
        }
        // 监听文件上传成功事件
        xhr4.upload.onload = function(){
            $('#percent').removeClass().addClass('progress-bar progress-bar-success');
        }

        xhr4.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar');
        xhr4.send(fd);

        xhr4.onreadystatechange = function(){
            if(xhr4.readyState == 4 && xhr4.status == 200){
                var data = JSON.parse(xhr4.responseText);
                if(data.status == 200){  //文件上传成功
                    console.log(data);
                    document.querySelector('#img').src = 'http://www.liulongbin.top:3006'+data.url;
                }else{
                    console.log('图片上传失败:' + data.message);
                }
            }
        }

    })


    
</script>

</body>
</html>